import {createRouter, createWebHistory} from 'vue-router'

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/LoginView.vue')
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('../views/RegisterView.vue')
    },
    {
        path: "/front",
        name: "Front",
        component: () => import('../views/FrontView.vue'),
        children: [
            {
                path: '/basic',
                name: 'Basic',
                component: () => import('../views/BasicView.vue')
            },
            {
                path: '/auth',
                name: 'Auth',
                component: () => import('../views/AuthView.vue')
            },
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})


router.beforeEach((to, from, next) => {
    // to，即将访问路由对象
    // from，当前正要离开路由
    // next() 继续向后执行，去to的页面
    // next(false) 不跳转，还在当前页面。
    // next("/xxx")  next({name:"xxx"})  next({pat:"/xxx"})
    let token = localStorage.getItem("token");
    if (token) {
        // 已登录，可以向目标地址访问
        next();
        return
    }
    // 未登录，登录页面
    if (to.name === "Login" || to.name === "Register") {
        next();
        return;
    }
    // 未登录，访问的其他地址
    next({name: "Login"});
})

export default router
